package com.ld.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.Optional;
import java.util.regex.Pattern;

public class CommonUtils {
    public static boolean isMatch(String pat, String v) {
        Pattern pattern = Pattern.compile(pat);
        int length = v.length();
        if (length == 0) return false;
        if (length == 1){
            return pattern.matcher(v).matches();
        }
        for (int i=0;i<length;i++){
            String s = String.valueOf(v.charAt(i));
            if (s.trim().length() <= 0) continue;
            if (!pattern.matcher(s).matches()){
                return false;
            }
        }
        return true;
    }

    public static Optional<String> englishWordSegmentation(String enWord){
        try {
            Pattern compile = Pattern.compile("[a-zA-Z]");
            Pattern capital = Pattern.compile("[A-Z]");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < enWord.length(); i++) {
                String v = String.valueOf(enWord.charAt(i));
                if (!compile.matcher(v).matches()){
                    String substring = sb.substring(sb.length() - 1);
                    if (!StringUtils.isBlank(substring)){
                        sb.append(" ");
                    }
                    continue;
                }
                if (capital.matcher(v).matches()){//capital
                    String substring = sb.substring(sb.length() - 1);
                    if (!StringUtils.isBlank(substring)){
                        sb.append(" ");
                    }
                    sb.append(v);
                }else {
                    sb.append(v);
                }
            }
            return Optional.ofNullable(sb.toString());
        }catch (Exception e){
            e.printStackTrace();
            return Optional.empty();
        }
    }
}
